<?php
/**
 * Created By PhpStorm
 * Author: patrick wu
 * Date: 2020/9/22
 * Time: 17:04
 */
namespace App\Service\Admin;

use App\Http\Model\Mysql\AttributeModel;

class AttributeService extends BaseService
{
    /**
     * 属性列表
     * @param int $page 当前页面
     * @param int $size 每页数量
     * @return array
     */
    public function attrList(int $page = 1, int $size = 0)
    {
        $size   =   $size <= 0 ? self::PAGE_LIMIT : $size;
        $count  =   AttributeModel::count();
        $list   =   AttributeModel::query()->limit($size)->offset(($page - 1) * $size)->select(['id' , 'attr_name', 'attr_en_name', 'sorting', 'shop_id', 'is_system', 'updated_at'])
                    ->orderBy('sorting', 'desc')->get()->each(function (&$item) {
                        $item->update_time  =   $item->updated_at->toDateTimeString();
                        unset($item->updated_at);
                    });

        if ($list->isEmpty()) {
            return [true, []];
        } else {
            return [true, [
                'count' =>  $count,
                'list'  =>  $list->toArray(),
                'pages' =>  ceil($count / $size),
                'current'=> $page
            ]];
        }
    }

    /**
     * 属性删除
     * @param int $attr_id 属性ID
     * @return array
     */
    public function attrDelete(int $attr_id)
    {
        $del_result =   AttributeModel::where(['id' => $attr_id])->delete();
        if ($del_result) {
            return [true, '删除成功'];
        } else {
            return [false, '删除失败'];
        }
    }

    /**
     * 属性添加
     * @param array $params 添加的内容
     * @return array
     */
    public function attrAdd(array $params)
    {
        $insert['attr_name']    =   $params['attr_name'];
        $insert['attr_en_name'] =   $params['attr_en_name'];
        $insert['sorting']      =   $params['sorting'] ?? 0;
        $insert['is_system']    =   $params['is_system'] ?? 0;
        $insert['shop_id']      =   $params['shop_id'] ?? 0;

        $insert_result  =   AttributeModel::create($insert);
        if ($insert_result) {
            return [true, '添加成功'];
        } else {
            return [false, '添加失败'];
        }
    }
}
